<template>
  <el-dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="110px"
      v-loading="formLoading"
    >
    <template v-if="dialogTitle=='编辑'">
      <el-form-item label="点检项目编码" prop="spotCheckProjectCode" >
        <el-input v-model="formData.spotCheckProjectCode" disabled  />
      </el-form-item>
    </template>
      <el-form-item label="点检项目名称" prop="spotCheckProjectName">
        <el-input v-model="formData.spotCheckProjectName" placeholder="请输入点检项目名称" />
      </el-form-item>
      <el-form-item label="判断基准" prop="criterion">
        <el-input v-model="formData.criterion" placeholder="请输入判断基准" type="textarea" />
      </el-form-item>
      <el-form-item label="部位" prop="part">
        <el-input v-model="formData.part" placeholder="请输入部位" />
      </el-form-item>
      <el-form-item label="实施时间" prop="implementationTime">
        <el-input v-model="formData.implementationTime" placeholder="请输入实施时间" />
      </el-form-item>
      <el-form-item label="点检方法" prop="spotCheckMethod">
        <el-input v-model="formData.spotCheckMethod" placeholder="请输入点检方法" />
      </el-form-item>
      <el-form-item label="实施周期" prop="dictImplementationCycle">
        <el-select v-model="formData.dictImplementationCycle" clearable placeholder="请选择周期">
          <el-option
            v-for="(dict, index) in getIntDictOptions('dict_implementation_cycle')"
            :key="index"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="填写类型" prop="dictFillingType">
        <el-select v-model="formData.dictFillingType" clearable placeholder="请选择类型">
          <el-option
            v-for="(dict, index) in getIntDictOptions('dict_filling_type')"
            :key="index"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="枚举" v-if="formData.dictFillingType=='10'">
    <div class="father_box" ref="tabBox">
    <!-- 生成的标签 -->
    <div v-for="(item, index) in TagsAll" :key="index" class="spanbox">
      <div v-if="item">
      <span class="tagspan">{{ item }}</span>
      <i class="span_close" @click="removeTag(index)"></i>
    </div>
    </div>
    <input
      :placeholder="placeholderText"
      v-model="inputTagValue"
      @keyup.enter="addTags"
      class="inputTag"
      ref="inputTag"
      type="text"
      @focus="focusPrice"
      @blur="blurPrice"
    />
  </div>

      </el-form-item>
      <el-form-item label="文本" v-else-if="formData.dictFillingType=='20'">  
    <el-input v-model="formData.enumeratedValues" type="textarea"/>
      </el-form-item>
      <el-form-item label="状态" prop="dictEnableStatus">
        <el-select v-model="formData.dictEnableStatus" clearable placeholder="请选择状态">
          <el-option
            v-for="(dict, index) in getIntDictOptions('dict_enable_status')"
            :key="index"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
          <el-input v-model="formData.remark" placeholder="请输入备注" type="textarea" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </el-dialog>
</template>
<script setup>
import { getIntDictOptions } from '@/utils/dict'
import * as DeviceCheckUpkeepApi from '@/api/config/deviceCheckUpkeep'

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const tabBox = ref()
const formData = ref({
  spotCheckProjectCode: undefined,
  spotCheckProjectName: undefined,
  spotCheckMethod: undefined,
  dictImplementationCycle: undefined,
  dictFillingType: undefined,
  enumeratedValues: undefined,
  criterion: undefined,
  remark: undefined,
  dictEnableStatus: undefined,
  implementationTime:undefined,
  part:undefined
})
const formRules = reactive({
  // checkProjectCode: [{ required: true, message: '点检项目编码不能为空', trigger: 'blur' }],
  spotCheckProjectName: [{ required: true, message: '点检项目名称不能为空', trigger: 'blur' }],
  criterion:[{required: true, message: '判断基准不能为空', trigger: 'blur'}],
  part: [{ required: true, message: '部位能为空', trigger: 'blur' }],
  implementationTime: [{ required: true, message: '实施时间不能为空', trigger: 'blur' }],
  spotCheckMethod: [{ required: true, message: '点检方法不能为空', trigger: 'blur' }],
  dictImplementationCycle: [{ required: true, message: '实施周期不能为空', trigger: 'change' }],
  dictFillingType: [{ required: true, message: '填写类型不能为空', trigger: 'change' }],
  dictEnableStatus: [{ required: true, message: '状态不能为空', trigger: 'change' }]
})
const formRef = ref() // 表单 Ref
//标签数组
let TagsAll =ref([])
//存放input数据
const inputTagValue = ref()
const placeholderText  = ref("输入后按'回车'创建'")
const inputTag = ref()
//添加tag
const addTags = ()=>{
  if (inputTagValue.value!== '') {
    placeholderText.value = ''
    TagsAll.value.push(inputTagValue.value); 
    inputTagValue.value = '';
    console.log(TagsAll.value,'TagsAll.value')
  }
};
//删除tag
const removeTag =(index)=>{
 if(TagsAll.value)TagsAll.value.splice(index,1)
 console.log(TagsAll.value)
 if(TagsAll.value.length==0)placeholderText.value="输入后按'回车'创建'"
}

const focusPrice = () =>{
  tabBox.value.style.border="1px solid #2cc0bc"
}

const blurPrice = () =>{
  tabBox.value.style.border="1px solid #dcdfe6"
}
/** 打开弹窗 */
const open = async (type, id) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  TagsAll.value=[]
  inputTagValue.value = ''
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await DeviceCheckUpkeepApi.getDeviceCheckUpkeep(id)
      if(formData.value.dictFillingType!==20&&formData.value.enumeratedValues){
      TagsAll.value=formData.value.enumeratedValues.split(',')
      console.log(formData.value.enumeratedValues,'formData.value.enumeratedValues')
      if(TagsAll.value.length!==0)placeholderText.value=''
      formData.value.enumeratedValues=undefined
      }
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗
//
/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  addTags()
  try {
    const data = formData.value
    
    // if(!data.enumeratedValues)data.enumeratedValues=TagsAll.value.toString()
    if(formData.value.dictFillingType=='10'){
      data.enumeratedValues=TagsAll.value.toString()
    }else{
      TagsAll.value=null
    }
    if (formType.value === 'create') {  
      await DeviceCheckUpkeepApi.createDeviceCheckUpkeep(data)
      TagsAll.value=null
      message.success(t('common.createSuccess'))
    } else {
      await DeviceCheckUpkeepApi.updateDeviceCheckUpkeep(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
  // checkProjectCode: undefined,
  spotCheckProjectName: undefined,
  spotCheckMethod: undefined,
  dictImplementationCycle: undefined,
  dictFillingType: undefined,
  enumeratedValues: undefined,
  criterion: undefined,
  remark: undefined,
  dictEnableStatus: undefined,
  implementationTime:undefined,
  part:undefined
  }
  formRef.value?.resetFields()
}
</script>
<style scoped>
/* 外层div */
.father_box {
  display:inline-block;
  width: 220px;
  box-sizing: border-box;
  background-color: white;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  font-size: 12px;
  text-align: left;
  padding-left: 5px;
  word-wrap: break-word;
  overflow: hidden;
}
/* 标签 */
.spanbox {
  display: inline-block;
  /* width:500px; */
  font-size: 14px;
  margin: 3px 4px 3px 0;
  background-color: #ecf5ff;
  border: 1px solid #e8eaec;
  border-radius: 3px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04)
}
/* 标签文字 */
.tagspan {
  height: 24px;
  line-height: 22px;
  max-width: 99%;
  position: relative;
  display: inline-block;
  padding-left: 8px;
  color: #2cc0bc;
  font-size: 14px;
  opacity: 1;
  vertical-align: middle;
  overflow: hidden;
  transition: 0.25s linear;
}
/* tag的叉叉 */
.span_close {
  padding: 0 6px 0 4px;
  opacity: 1;
  -webkit-filter: none;
  filter: none;
  color: #2cc0bc;
  /* font-weight: 600; */
  cursor:pointer;
}
/* 鼠标经过叉叉 */
.span_close:hover{
  /* background-color: #409EFF; */
  /* border-radius: 50%; */
  color: #55dddd;
}
.span_close:after {
  content: "\00D7";
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  /* line-height: 27px; */
  transition: 0.3s, color 0s;
}
/* input */
.inputTag {
  font-size: 16px;
  border: none;
  box-shadow: none;
  outline: none;
  background-color: transparent;
  padding: 0;
  width: 100px;
  /* min-width: 150px; */
  vertical-align: top;
  /* height: 32px; */
  color: #495060;
  /* line-height: 32px; */
}
/* 输入框提示文字大小 */
input:placeholder-shown {
font-size: 16px;
}

</style>